package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.mapper.AddressBookMapper;
import com.itheima.reggie.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public List<AddressBook> addressList(Long userId) {
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,userId);
        List<AddressBook> addressBooks = addressBookMapper.selectList(lqw);
        return addressBooks;
    }

    @Override
    public void setDefaultAddress(AddressBook address) {
        AddressBook addressBook = new AddressBook();
        addressBook.setIsDefault(0);
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,address.getUserId());
        lqw.eq(AddressBook::getIsDefault, 1);
        addressBookMapper.update(addressBook, lqw);
        address.setIsDefault(1);
        addressBookMapper.updateById(address);
    }

    @Override
    public void addAddress(AddressBook addressBook) {
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,addressBook.getUserId());
        AddressBook address = addressBookMapper.selectOne(lqw);
        if(address==null){
            addressBook.setIsDefault(1);
        }
        addressBookMapper.insert(addressBook);
    }

    @Override
    public AddressBook addressFindOne(Long id) {
        AddressBook addressBook = addressBookMapper.selectById(id);
        return addressBook;
    }

    @Override
    public void updateAddress(AddressBook addressBook) {
        addressBookMapper.updateById(addressBook);
    }

    @Override
    public AddressBook getDefaultAddress(Long userId) {
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,userId);
        lqw.eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookMapper.selectOne(lqw);
        return addressBook;
    }
    //删除收货地址
    @Override
    public void removeAddress(Long ids) {
        addressBookMapper.deleteById(ids);
    }
}
